package zpy.servlet.servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import zpy.servlet.pojo.AjaxResult;
import zpy.servlet.pojo.Student;

import java.io.File;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Paths;


/**
 * Servlet implementation class FileUploadAjaxServlet
 */
@WebServlet("/fileUploadAjaxServlet")
@MultipartConfig(
        fileSizeThreshold = 1024 * 10,    // 10KB
        maxFileSize = 1024 * 1024 * 20,   // 20MB
        maxRequestSize = 1024 * 1024 * 1024 // 1GB
)
public class FileUploadAjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void init() throws ServletException {
        // 创建上传目录
        String imgUploadPath = getServletContext().getInitParameter("imgUploadPath");
        File tempFile = new File(imgUploadPath);
        if (!tempFile.exists()) {
            tempFile.mkdirs();
        }
    }

    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadAjaxServlet() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/plain;charset=utf-8");

        // 检查是否为multipart内容
        if (!request.getContentType().startsWith("multipart/")) {
            AjaxResult result = new AjaxResult(500,"不是文件上传",null);
            Gson gson = new Gson();
            Writer writer = response.getWriter();
            writer.write(gson.toJson(result));
            return;
        }

        try{
            Student student = new Student();
            // 获取普通表单字段
            String name = request.getParameter("name");
            String num = request.getParameter("num");
            student.setName(name);
            student.setNum(num);

            // 获取文件part
            Part photoPart = request.getPart("photo");

            if (photoPart == null || photoPart.getSubmittedFileName() == null ||
                    photoPart.getSubmittedFileName().isEmpty()) {
                AjaxResult result = new AjaxResult(500,"没有文件名",null);
                Gson gson = new Gson();
                Writer writer = response.getWriter();
                writer.write(gson.toJson(result));
                return;
            }

            // 获取文件名和后缀
            String fileName = Paths.get(photoPart.getSubmittedFileName()).getFileName().toString();
            String fileSuffix = fileName.substring(fileName.lastIndexOf("."));

            // 构建保存路径
            String imgUploadPath = getServletContext().getInitParameter("imgUploadPath");
            File savePath = new File(imgUploadPath);
            File file = new File(savePath, student.getName() + fileSuffix);

            // 保存文件
            photoPart.write(file.getAbsolutePath());

            // 设置学生照片路径
            String imgUrlPrefix = getServletContext().getInitParameter("imgUrlPrefix");
            student.setPhoto(imgUploadPath + "\\" + student.getName() + fileSuffix);
            student.setPhotoUrl(imgUrlPrefix + student.getName() + fileSuffix);

            AjaxResult result = new AjaxResult(200,"照片上传成功",student);
            Gson gson = new Gson();
            Writer writer = response.getWriter();
            writer.write(gson.toJson(result));
        }catch(Exception e){
            e.printStackTrace();
            AjaxResult result = new AjaxResult(500,"文件上传失败",null);
            Gson gson = new Gson();
            Writer writer = response.getWriter();
            writer.write(gson.toJson(result));
            return;
        }
    }

}
